package com.gary.shiro.controller;

import com.gary.shiro.entity.ApiResult;
import com.gary.shiro.param.LoginParam;
import com.gary.shiro.po.Permission;
import com.gary.shiro.po.User;
import com.gary.shiro.service.LoginService;
import com.gary.shiro.service.PermissionService;
import com.gary.shiro.service.RoleService;
import com.gary.shiro.service.UserRoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author peng_rui
 * @date 2022/3/26
 */
@RestController
@RequestMapping(value = "/api/gary/shiro/admin")
public class LoginController {

    @Resource
    private LoginService loginService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private RoleService roleService;
    @Resource
    private PermissionService permissionService;

    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public ApiResult<String> login(@Validated @RequestBody LoginParam param) {
        loginService.login(param);
        return ApiResult.success("SUCCESS");
    }

    @RequestMapping(path = "/logout", method = RequestMethod.GET)
    public ApiResult<String> logout() {
        loginService.logout();
        return ApiResult.success( "SUCCESS");
    }

    /**
     * 获取登录用户的信息
     *
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(path = "/info", method = RequestMethod.GET)
    public ApiResult<Map<String, Object>> info() {
        Subject currentUser = SecurityUtils.getSubject();
        User user = (User) currentUser.getPrincipal();
        Map<String, Object> data = new HashMap<>();
        data.put("realName", user.getRealName());
        data.put("username", user.getUsername());
        List<Long> roleIds = userRoleService.queryRoleIdsByUserId(user.getId());
        Set<String> roles = roleService.queryRoleByIds(roleIds);
        Set<String> permissions = permissionService.queryPathByRoleIds(roleIds);
        data.put("roles", roles);
        data.put("perms", permissions);
        return ApiResult.success(data);
    }
}
